<?php
/**
 * Head First 设计模式
 * 第二章： 观察者模型
 * 气象站例子 ── WeatherData 主题
 */
include_once 'interface.php';

/**
 * 气象站主题
 */
class WeatherData implements Subject {
	/**
	 * 温度、湿度、气压
	 */
	private $temperature;
	private $humidity;
	private $pressure;
	
	/**
	 * Array 观察者列表
	 */
	private $observers;
	
	/**
	 * 构造函数，初始化$observers数组
	 */
	public function __construct() {
		$this->observers = array();
	} //END func __construct
	
	/**
	 * @see Subject::registerObserver()
	 *
	 * @param Observer $o
	 */
	public function registerObserver(Observer $o) {
		//if (isset($this->observers))
			array_push($this->observers, $o);
		//else 
			//$this->observers = array($o);
	} //END func registerObserver
	
	/**
	 * @see Subject::removeObserver()
	 *
	 * @param Obsever $o
	 */
	public function removeObserver(Observer $o) {
		/**
		 * 删除数组中的元素
		 */
		foreach ($this->observers as $key => $value) {
			if ($value == $o) {
				unset($this->observers[$key]);
				reset($this->observers);
				break;
			}
		} //END foreach observer
	} //END func removeObserver

	/**
	 * @see Subject::notifyObserver()
	 *
	 */
	public function notifyObserver() {
		//var_dump($this->observers);
		/*for ($i = 0; $i < count($this->observers); $i++) {
			$this->observers[$i]->update($this->temperature, $this->humidity, $this->pressure);
		}*/
		foreach ($this->observers as $key => $value) {
			$this->observers[$key]->update($this->temperature, $this->humidity, $this->pressure);
		}
	} //END func notfiyObserver	
	
	/**
	 * 气象站更新数据后，通知所有订阅者
	 */
	public function measurementsChanged() {
		$this->notifyObserver(); 
	} //END func measurementChanged
	
	/**
	 * 设置数据更新
	 * 
	 * @param string $temperature, $humidity, $pressure
	 */
	public function setMeasurements($temperature, $humidity, $pressure) {
		$this->temperature = $temperature;
		$this->humidity = $humidity;
		$this->pressure = $pressure;
		$this->measurementsChanged();
	} //END func setMeasurements
} //END class WeatherData
?>